/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.analysys.presto.connector.hbase;

import com.analysys.presto.connector.hbase.meta.TableMetaInfo;
import com.analysys.presto.connector.hbase.utils.Utils;
import com.facebook.presto.spi.ColumnMetadata;
import com.google.common.collect.ImmutableList;
import io.airlift.log.Logger;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.hbase.HTableDescriptor;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.analysys.presto.connector.hbase.utils.Constant.DEFAULT_HBASE_NAMESPACE_NAME;

/**
 * HBase table
 *
 * @author wupeng
 * @date 2019/01/29
 */
public class HBaseTable {

    public static final Logger logger = Logger.get(HBaseTable.class);

    /**
     * 表模型
     */
    private final HTableDescriptor hTableDescriptor;


    private final List<ColumnMetadata> columnsMetadata;


    /**
     * meta文件的修改日期
     */
    private long lastModify = 0L;

    public HBaseTable(String schemaName, HTableDescriptor tabDesc, HBaseConfig config) {
        this.hTableDescriptor = Objects.requireNonNull(tabDesc, "tabDesc is null");
        ImmutableList<ColumnMetadata> tableMeta = null;
        try {
            schemaName = StringUtils.isBlank(schemaName) ? DEFAULT_HBASE_NAMESPACE_NAME : schemaName;

            String tableName = getTableName().contains(":") ?
                    getTableName().split(":")[1] : getTableName();

            // 从 JSON 文件中获取 meta 信息
            final Map<String, TableMetaInfo> metaInfoMap = Utils.listTableMetaInfoFromJson(schemaName, config.getMetaDir());
            // 从 Hbase meta 中获取的表信息
            String schemaAndName = schemaName + ":" + tableName;
            for (Map.Entry<String, TableMetaInfo> entry : metaInfoMap.entrySet()) {
                if(schemaAndName.startsWith(entry.getKey())) {
                    this.lastModify = entry.getValue().getLastModify();
                    tableMeta = Utils.getColumnMetaFromJson(schemaName, tableName, config.getMetaDir());
                    break;
                }
            }

            if (tableMeta == null || tableMeta.size() <= 0) {
                logger.error("OOPS! Table meta info cannot be NULL, table name=" + getTableName());
                throw new IllegalStateException("Cannot find meta info of table " + getTableName() + ".");
            }
        } catch (Exception e) {
            logger.error(e, e.getMessage());
        }
        this.columnsMetadata = tableMeta;
    }

    public String getTableName() {
        return this.hTableDescriptor.getTableName().getNameAsString();
    }

    List<ColumnMetadata> getColumnsMetadata() {
        return this.columnsMetadata;
    }


    public long getLastModify() {
        return lastModify;
    }
}
